import 'package:flui/flui.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:fzcgx_app/network/http.dart';
import 'package:fzcgx_app/router/routes.dart';
import 'package:fzcgx_app/ui/base/base_view_model.dart';

class LoginViewModel extends BaseViewModel {
  TextEditingController phoneControll = TextEditingController();
  TextEditingController pswControll = TextEditingController();
  bool pswObscureText;
  bool isInput;
  bool loading = false;
  LoginViewModel() {
    this.pswObscureText = true;
    this.isInput = false;
  }

  void onChanged() {
    checkInput();
  }

  void clearPhoneText() {
    this.phoneControll.clear();
    checkInput();
    notifyListeners();
  }

  void clearPswText() {
    this.pswControll.clear();
    checkInput();
    notifyListeners();
  }

  void onPswObscureText() {
    this.pswObscureText = !pswObscureText;

    notifyListeners();
  }

  void checkInput() {
    if (this.phoneControll.text.isNotEmpty &&
        this.pswControll.text.isNotEmpty) {
      this.isInput = true;
    } else {
      this.isInput = false;
    }
    notifyListeners();
  }

  void onLoad() {
    loading = true;
    notifyListeners();
  }

  void onLogin(BuildContext context) {
    var dismiss = FLToast.loading(text: '正在登录...');
    Http.instance.post(
        'member/login', {'phone': phoneControll.text, 'pwd': pswControll.text},
        onSuccess: (data) {
      dismiss();
      SpUtil.putString('phone', data['phone']);
      SpUtil.putString('type', data['type'].toString());
      SpUtil.putString('uid', data['id']);
      SpUtil.putString('avatar', data['head']);
      SpUtil.putString('token', data['token']);
      FLToast.success(text: '登录成功');
      Routes.goBack(context);
    }, onError: (error) {
      dismiss();
    }, onFail: (fail) {
      dismiss();
    });
  }
}
